package com.getpebble.android.framework.pebblekit;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.CursorWindow;
import android.database.MatrixCursor;
import android.database.MatrixCursor.RowBuilder;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.ConnectionStatus;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.framework.util.PebbleCapabilities;
import com.sun.mail.smtp.SMTPMessage;
import java.lang.ref.SoftReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class PebbleKitProvider extends ContentProvider {
    private static final String[] COLUMNS = new String[]{"isConnected", "supportsAppMessages", "supportsDataLogging", "versionMajor", "versionMinor", "versionPoint", "versionTag"};
    private static final String TAG = PebbleKitProvider.class.getSimpleName();
    private static Handler sCleanupHandler = new Handler(Looper.getMainLooper());
    private static final Queue<CursorRef> sCursorRefs = new LinkedList();
    private static final UriMatcher sUriMatcher = new UriMatcher(-1);

    private static class CursorRef {
        private final SoftReference<Cursor> mCursorRef;
        private final String mPkg;
        private final CursorWindow mWindow;

        CursorRef(String pkg, Cursor cursor, CursorWindow window) {
            this.mPkg = pkg;
            this.mCursorRef = new SoftReference(cursor);
            this.mWindow = window;
        }

        void close() {
            Cursor cursor = (Cursor) this.mCursorRef.get();
            if (!(cursor == null || cursor.isClosed())) {
                Trace.debug(PebbleKitProvider.TAG, "Closing cursor " + cursor + " for pkg " + this.mPkg);
                cursor.close();
            }
            if (this.mWindow != null) {
                this.mWindow.clear();
                this.mWindow.close();
            }
        }
    }

    private static class PebbleMatrixCursor extends MatrixCursor {
        private CursorWindow mWindow;

        public PebbleMatrixCursor(String[] columnNames, int initialCapacity) {
            super(columnNames, initialCapacity);
        }

        CursorWindow createWindow() {
            this.mWindow = new CursorWindow("PebbleKitWindow");
            fillWindow(0, this.mWindow);
            return this.mWindow;
        }

        public CursorWindow getWindow() {
            CursorWindow window = this.mWindow;
            this.mWindow = null;
            return window;
        }

        public void fillWindow(int position, CursorWindow window) {
            super.fillWindow(position, window);
        }
    }

    static {
        sUriMatcher.addURI("com.getpebble.android.provider", "state", 1);
    }

    public boolean onCreate() {
        return true;
    }

    protected PblDeviceRecord getLastConnectedDeviceRecord() {
        return PebbleApplication.getLastConnectedDeviceRecord();
    }

    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        switch (sUriMatcher.match(uri)) {
            case SMTPMessage.RETURN_FULL /*1*/:
                int i;
                Trace.verbose(TAG, "3rd-party querying state");
                Cursor pebbleTimeCursor = getContext().getContentResolver().query(PebbleKitConstants.URI_CONTENT_BASALT, null, null, null, null);
                if (pebbleTimeCursor != null) {
                    Trace.verbose(TAG, "Pebble Time content provider detected");
                    if (pebbleTimeCursor.moveToFirst() && pebbleTimeCursor.getInt(0) == 1) {
                        Trace.verbose(TAG, "Pebble Time connected; forwarding query");
                        pebbleTimeCursor.moveToPrevious();
                        return pebbleTimeCursor;
                    }
                    pebbleTimeCursor.close();
                }
                PebbleMatrixCursor c = new PebbleMatrixCursor(COLUMNS, COLUMNS.length);
                boolean isConnected = false;
                boolean supportsAppMessages = false;
                boolean supportsDataLogging = false;
                int majorVersion = 0;
                int minorVersion = 0;
                int pointVersion = 0;
                String versionTag = "";
                PblDeviceRecord lastConnectedDeviceRecord = getLastConnectedDeviceRecord();
                if (lastConnectedDeviceRecord != null) {
                    isConnected = ConnectionStatus.CONNECTED.equals(lastConnectedDeviceRecord.connectionStatus);
                    if (lastConnectedDeviceRecord.fwVersion != null) {
                        supportsAppMessages = PebbleCapabilities.remoteSupportsAppMessage(lastConnectedDeviceRecord.fwVersion);
                        supportsDataLogging = PebbleCapabilities.remoteSupportsSpooling(lastConnectedDeviceRecord.fwVersion);
                        majorVersion = lastConnectedDeviceRecord.fwVersion.getMajor();
                        minorVersion = lastConnectedDeviceRecord.fwVersion.getMinor();
                        pointVersion = lastConnectedDeviceRecord.fwVersion.getPoint();
                        versionTag = lastConnectedDeviceRecord.fwVersion.getVersionTag();
                    }
                }
                RowBuilder newRow = c.newRow();
                if (isConnected) {
                    i = 1;
                } else {
                    i = 0;
                }
                newRow = newRow.add(Integer.valueOf(i));
                if (supportsAppMessages) {
                    i = 1;
                } else {
                    i = 0;
                }
                newRow = newRow.add(Integer.valueOf(i));
                if (supportsDataLogging) {
                    i = 1;
                } else {
                    i = 0;
                }
                newRow.add(Integer.valueOf(i)).add(Integer.valueOf(majorVersion)).add(Integer.valueOf(minorVersion)).add(Integer.valueOf(pointVersion)).add(versionTag);
                CursorWindow window = c.createWindow();
                String pkg = null;
                if (VERSION.SDK_INT >= 19) {
                    pkg = getCallingPackage();
                }
                CursorRef cursorRef = new CursorRef(pkg, c, window);
                synchronized (sCursorRefs) {
                    if (sCursorRefs.size() > 50) {
                        ((CursorRef) sCursorRefs.poll()).close();
                    }
                    sCursorRefs.add(cursorRef);
                    sCleanupHandler.removeCallbacksAndMessages(null);
                    sCleanupHandler.postDelayed(new Runnable() {
                        public void run() {
                            synchronized (PebbleKitProvider.sCursorRefs) {
                                Iterator<CursorRef> iter = PebbleKitProvider.sCursorRefs.iterator();
                                while (iter.hasNext()) {
                                    ((CursorRef) iter.next()).close();
                                    iter.remove();
                                }
                            }
                        }
                    }, 120000);
                }
                return c;
            default:
                Trace.warning(TAG, "Unknown Uri: " + uri);
                return null;
        }
    }

    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
            case SMTPMessage.RETURN_FULL /*1*/:
                return "vnd.android.cursor.item/vnd.com.getpebble.android.provider.state";
            default:
                return null;
        }
    }

    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }
}
